<?php
/**
 * 获取类中的所有方法
 * @param $class
 * @return mixed
 */
function get_class_all_methods($class){
    $r = new ReflectionClass($class);
    $method_arr = array();//public 方法列表
    $methods = array();//当前方法信息
    foreach($r->getMethods() as $key=>$methodObj){
        if($methodObj->isPrivate()){
            $methods[$key]['type'] = 'private';
        }elseif($methodObj->isProtected()){
            $methods[$key]['type'] = 'protected';
        }else{
            $methods[$key]['type'] = 'public';
            $method_arr[] =  $methodObj->name;
        }
        $methods[$key]['name'] = $methodObj->name;
        $methods[$key]['class'] = $methodObj->class;
    }
    return $method_arr;
    //return $methods;
}

function e($s){
    echo $s,'<br/>';
}

function d($info = null, $time = false)
{
    if (! DEBUG)
        return;
    static $debug_info = array();
    if ($info != 'get_debug_data')
    {
        $debug_info[] = array('info'=>$info, 'backtrace'=>debug_backtrace());
        if ($time)
            time_debug('debug_time_' . count($debug_info));
    }

    return $debug_info;
}

function time_debug($name = null)
{
    static $start_time;
    if (! $start_time)
        $start_time = microtime(true);
    static $debug_points;
    if (! $debug_points)
        $debug_points = array();
    if (! $name)
        return $debug_points;
    $last_time = $debug_points[count($debug_points)-1]['offset_time'];
    $debug_points[] = array(
        'name'  =>  $name,
        'offset_time'  =>  microtime(true) - $start_time,
        'exec_time'  =>  microtime(true) - $start_time - $last_time,
    );

    return $debug_points;
}
/*
 * 通用日志记录方法(文件方式记录)
 * @param info
 */
function l($info, $file = 'info', $log_type = 'file')
{
    $debug = debug_backtrace();
    if (count($debug) > 1)
        $debug = $debug[1];
    else
        $debug = $debug[0];

    $time = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'];
    $url = $_SERVER['REQUEST_URI'];
    $file_name = $debug['file'];
    $line = $debug['line'];
    $function = $debug['function'];
    $info = is_string($info) ? $info : var_export($info, true);

    $server_addr = $_SERVER['SERVER_ADDR'];

    $str = 'Time:' . $time . ', ' .
        'Server:' . $server_addr . ', ' .
        'IP:' . $ip . ', ' .
        'URL:' . $url . ', ' .
        'File:' . $file_name . ', ' .
        'Line:' . $line . ', ' .
        'Function:' . $function . ', ' .
        'Info:' . $info . "\n";
    file_put_contents(LOG_PATH . $file . '.log', $str, FILE_APPEND);

}

function isCli() {
    return PHP_SAPI == 'cli' && empty($_SERVER['REMOTE_ADDR']);
}

function p($info, $exit = true, $ret = false)
{
    if (defined('RUNNING_MODE') && RUNNING_MODE == 'dev') {
        $debug  = debug_backtrace();
        $output = '';

        if (isCli()) {
            $output .= '[TRACE]' . PHP_EOL;
            foreach ($debug as $v) {
                $output .= 'File:' . $v['file'];
                $output .= 'Line:' . $v['line'];
                $output .= 'Args:' . implode(',', $v['args']) . PHP_EOL;
            }
            $output .= '[Info]' . PHP_EOL;
            $output .= var_export($info, true) . PHP_EOL;
        } else {
            foreach ($debug as $v) {
                $output .= '<b>File</b>:' . $v['file'] . '&nbsp;';
                $output .= '<b>Line</b>:' . $v['line'] . '&nbsp;';
                $output .= $v['class'] . $v['type'] . $v['function'] . '(\'';
                $output .= implode('\',\' ', $v['args']);
                $output .= '\')<br/>';
            }
            $output .= '<b>Info</b>:<br/>';
            $output .= '<pre>';
            $output .= var_export($info, true);
            $output .= '</pre>';
        }

        if ($ret)
            return $output;
        else
            echo $output;
        if ($exit)
            exit;
    } else {
        return;
    }
}

function loadModule($module, $params = array())
{
    global $_user, $_session;

    if ($params)
    {
        extract($params);
    }

    $content = '';
    if (file_exists($module_file = MODULE_PATH . $module . '.php'))
    {
        ob_start();
        include $module_file;
        $content = ob_get_contents();
        ob_end_clean();
    }
    return $content;
}

function module($module, $params = array(), $cache_name = '', $expire = -1)
{
    if (! $cache_name)
        $cache_name = $module;

    $content = '';
    if ($expire < 0)
    {
        // no cache need
        $content = loadModule($module, $params);
    }
    else
    {
        // need cache for expire time
        if (! ($content = cache('cache:' . $cache_name)))
        {
            // no cache or cache expire out
            $content = loadModule($module, $params);

            cache('cache:' . $cache_name, $content, $expire);
        }
    }
    return $content;
}

function gbk2utf8($data)
{
    if (is_array($data))
    {
        return array_map('gbk2utf8', $data);
    }
    else if (is_object($data))
    {
        return array_map('gbk2utf8', get_object_vars($data));
    }
    return mb_convert_encoding($data, 'UTF-8', 'GBK');
}

function utf8togbk($data)
{
    if (is_array($data))
    {
        return array_map('utf8togbk', $data);
    }
    else if (is_object($data))
    {
        return array_map('utf8togbk', get_object_vars($data));
    }
    return mb_convert_encoding($data, 'GBK','UTF-8');
}
// short function
function ifset($array, $key, $default = null)
{
    return isset($array[$key]) ? $array[$key] : $default;
}

function isUrl($url)
{
    return preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i',$url);
}


//截取中文字符,支持一个英文算两个字符，如果两个英文算一个字的截取传入280即可代表140
function cnSubStr($string,$sublen,$tip='')
{
    $len = strlen($string);
    if($sublen>=$len)
    {
        return $string;
    }
    $s="";
    for($i=0;$i<$sublen;$i++)
    {
        if(ord($string{$i})>127)
        {
            $s.=$string{$i}.$string{++$i};
            continue;
        }else{
            $s.=$string{$i};
            continue;
        }
    }

    if(strlen($s) >= $len)
        return $s;
    return $s.$tip;
}


function curl_get_contents($url, $timeout = 5){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');
//    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    @curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, true);
    curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 86400); // 缓存一天
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function curl_post_contents($url, $data = array(), $cookiepath = ''){
    $userAgent = 'Mozilla/4.0+(compatible;+MSIE+6.0;+Windows+NT+5.1;+SV1)';
    $referer = $url;
    if(!is_array($data) || !$url) return '';
    $post = '';
    foreach($data as $key => $value){
        $post .= $key . '=' . urlencode($value) . '&';
    }
    rtrim($post, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);				//设置访问的url地址
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);				//设置超时
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);	//用户访问代理 User-Agent
    curl_setopt($ch, CURLOPT_REFERER, $referer);		//设置 referer
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);		//跟踪301
    curl_setopt($ch, CURLOPT_POST, 1);					//指定post数据
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);		//添加变量
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiepath);	//COOKIE的存储路径,返回时保存COOKIE的路径
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		//返回结果
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

// gbk的explode，多字节处理，防止5c问题发生
function gbk_explode($l,$s) {
    $s = mb_convert_encoding($s, "utf-8", "GBK");
    $a = explode($l,$s);
    foreach($a as &$v){
        $v = mb_convert_encoding($v, "GBK", "utf-8");
    }
    return $a;
}

//字符串转数组
function stringToArray($str, $sign = '|', $break = ','){
    $arr = gbk_explode($sign, $str);
    if($break){
        foreach($arr as $value) {
            if($value){
                $data[] = explode($break, $value);
            }
        }
    }
    return $break ? $data : $arr;
}

//按照KEY取出数组重复
function array_union_key($a,$b) {
    return array_merge(array_diff_key($a,$b),$b);
}

// array_diff's bug for PHP5.2.6-5.3.3
function my_array_diff($a1, $a2)
{
    $a2 = array_flip((array)$a2);
    foreach ((array)$a1 as $key => $item)
    {
        if (isset($a2[$item]))
        {
            unset($a1[$key]);
        }
    }
    return $a1;
}

//取得URL的主域名
function is_domain($url){
    $tmp =  parse_url($url);
    $tmp_host = array_reverse(explode('.',$tmp['host']));
    $host_domain = $tmp_host[1].'.'.$tmp_host[0];
    if($host_domain =='whoopsfeed.com')
        return true;
    else
        return false;
}

/**
 * 跳转页面--重定向
 * @param  string $url
 * @param int $status 301 永久跳转 302 暂时跳转
 * @return void
 */
function redirect($url, $status = 302) {
    header('Status: ' . $status);
    header('Location: ' . $url);
    exit();
}

function return_ip()
{
    $ip = "0.0.0.0";
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        $ip_a = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']) ;
        for($i=0;$i<count($ip_a);$i++)
        {
            $tmp = trim($ip_a[$i]) ;
            if($tmp=='unknown'||$tmp=='127.0.0.1'||strncmp($tmp,'10.',3)==0||strncmp($tmp,'172',3)==0||strncmp($tmp,'192',3)==0)
                continue ;
            $ip = $tmp;
            break ;
        }
    }
    else if(!empty($_SERVER['HTTP_CLIENT_IP']))
    {
        $ip = trim($_SERVER['HTTP_CLIENT_IP']);
    }
    else if (!empty($_SERVER['REMOTE_ADDR']))
    {
        $ip = trim($_SERVER['REMOTE_ADDR']);
    }

    return $ip;
}

/**
 * 判读是否是 Ajax 请求
 * @return boolean
 */
function isAjax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');
}

/**
 * 过虑HTML
 * @param  string $var
 * @return string
 */
function htmlFilter($var) {
    $search = array (
        "'<script[^>]*?>.*?<\/script>'si",
        "'<html[^>]*?>.*?<body[^>]*?>'si",
        "'<\/body>.*?<\/html>'si",
        "'<style[^>]*?>.*?<\/style>'si",
        "'<link[^>]*?\s*[\/]?>'si",
        "'<iframe[^>]*?>.*?<\/iframe>'si",
        "'<form[^>]*?>(.*?)<\/form>'si",
        "'<textarea[^>]*?>.*?<\/textarea>'si",
        //"'\s*id\s*=\s*[\"|\'].*?[\"|\']'si",
        //"'\s* clas\s*s\s*=\s*[\"|\'].*?[\"|\']'si",
        //"'<!--.*?-->'si",
    );
    $replace = array ('', '', '', '', '', '', '', '', '', '', '');
    $var = preg_replace ($search, $replace, $var);
    $trans = array(
        '?' => '&#63;',
        '\\' => '&#92;',
        '`'=>'',
    );
    return strtr($var, $trans);
}

/*
 * 对二维数组,按第二维数组中的某个键值对进行排序
 * @param array $arr 二维数组如 array('0'=> array('v_title' => '视频2','v_image'=>'地址2','v_sort'=>'2'),'1'=>array('v_title' => '视频1','v_image'=>'地址1','v_sort'=>'1'))
 * @param string 二维数组中的某个键值对 如（v_sort）
 * @param int $sort_flags 排序方式 0:升序，1:降序
 * @return array 排序后的数二维数组
 * @date 2011-09-22
 * @ + 增加一个排序方式，
 */
function array_sort($arr,$field,$sort_flags =0){
    $sort_tmp =array();
    $arr_tmp  =array();
    foreach($arr as $key=>$value){
        $sort_tmp[$key]=$value[$field];//取出排列顺序字段
    }
    asort($sort_tmp);//按值排序，保留键的对应,可校正排序相同的情况
    foreach($sort_tmp as $k=>$v){
        $arr_tmp[] = $arr[$k] ;
    }
    return $sort_flags ? array_reverse($arr_tmp): $arr_tmp ;
}


/**
 * 处理XML JSON返回格式
 * @param $data
 * @param $format
 * @param string $jsonp
 * @return string
 */
function formatData($data, $format, $jsonp = ""){
    $data = gbk2utf8($data);
    if($format == "json"){
        return json_encode(($data));
    }
    if($format == "xml"){
        $xml= "<?xml version=\"1.0\" encoding=\"utf-8\" ?> ";
        $xml.="<response>";
        $xml.= formatXml($data);
        $xml.="</response>";
        return $xml;
    }
    if ($format =="jsonp" ){
        return $jsonp."('".json_encode($data)."')";
    }
}
/**
 * 处理xml的方法
 * @param $data
 * @return string
 */
function formatXml($data){
    $xml = '';
    foreach($data as $key=>$val){
        $xml.="<{$key}>";
        if(is_array($val)){
            $xml.= formatXml($val);
        }
        else{
            $xml.="{$val}";
        }
        $xml.="</{$key}>";
    }
    return $xml;
}

function toXml($data,$xml_setting=array(),& $xml=null,& $parent_node = null){
    $xml_setting_default = array('root'=>'xml','charset'=>'utf-8','num_key'=>'item','version'=>'1.0');
    $xml_setting         = is_array($xml_setting) ? $xml_setting : array() ;
    $xml_setting         = array_merge($xml_setting_default,$xml_setting);
    if($xml == null){
        $xml               =  new DOMDocument($xml_setting['version'],$xml_setting['charset']);
        $xml->formatOutput = false;
        $parent_node       = $xml->createElement($xml_setting['root']);
        $xml->appendChild($parent_node);
    }
    if($xml == null || $parent_node == null ){
        return false;
    }
    foreach($data as $key => $value){
        $node_name  = is_numeric($key) ? $xml_setting['num_key'] : $key;
        $node       = $xml->createElement($node_name);
        $parent_node->appendChild($node);
        if(!is_array($value)){
            $child_node  = $xml->createTextNode($value);
            $node->appendChild($child_node);
        }else{
            $child_node  = toXml($value,$xml_setting,$xml,$node);
        }

    }
    return $xml->saveXML();
}

//去除空格
function trim_space($s) {
    $s = mb_ereg_replace('^(　| )+', '', $s);
    $s = mb_ereg_replace('(　| )+$', '', $s);
    return $s;
}

//创建文件夹
function mkdirs($dir, $mode=0777){

    if (is_dir($dir) || @mkdir($dir,$mode,true)){
        @chmod($dir,$mode);
        return true;
    }
    if (!mkdirs(dirname($dir),$mode)){
        return false;
    }

    if(@mkdir($dir,$mode,true)){
        @chmod($dir,$mode);
        return true;
    }else{
        return false;
    }
}


function alert ($msg)
{
    $str = '<script type="text/javascript">alert('.$msg.');</script>';

    echo $str;
}

function content_preg_img($content,$time = null)
{
    $dir_y = date('Y');
    $dir_m = date('m');
    $dir_d = date('d');

    $data_str = $dir_y.'/'.$dir_m.'/'.$dir_d;
    $data_time_str = date('YmdHis');
    if($time != null){
        $dir_y = date('Y',strtotime($_GET['time']));
        $dir_m = date('m',strtotime($_GET['time']));
        $dir_d = date('d',strtotime($_GET['time']));
        $data_str = $dir_y.'/'.$dir_m.'/'.$dir_d;
        $data_time_str = date('YmdHis',strtotime($time));
    }
    $img_exist = is_int(strpos($content, '<img'));

    $new_content = '';
    if ($img_exist) {
        //取出所有img标签并匹配其链接
        $preImg = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg]))[\'|\"].*?[\/]?>/";
        preg_match_all($preImg, $content, $arr); //$content为原始文章内容，下同

        foreach ($arr[1] as $v) {
            //读取图片
            $img = file_get_contents($v);
            //获取图片名
            $picName = pathinfo($v);
            //创建图片文件到本地
            $dir = 'uploads/news/'.$data_str.'/';
            $file_name = $data_time_str . '_' . rand(1,999999999) . '.' . $picName['extension'];
            $file_name = explode('!',$file_name);
            $file_name = $file_name[0];
            if (!file_exists($dir)) {
                mkdir($dir,0777,true);
            }

            if(!file_exists($dir . $file_name)){
                file_put_contents($dir . $file_name, $img);
            }
            $namePic[] = $dir . $file_name;
        }

        //替换所有图片链接为本地链接
        $new_content = str_replace($arr[1], $namePic, $content); //$con为被替换链接地址之后的文章内容
    } else {
        $new_content = $content;
    }

    return $new_content;
}

/**
 * 显示转换方法 1=》待审核
 * @param $key
 * @param $arr
 * @return string
 */
function changeShow($key,$arr){
    return isset($arr[$key]) ? $arr[$key] :  '未知';
}